<script>
export default {
  name: "course",
  data() {
    return {
      courses: [],
      activityName: "",
      courseName: "",
      status: "",
      teacherName: "",

      selectedCourses: [],
      pagination: {
        currentPage: 1,
        pageSize: 5,
        total: 0
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogTitle: '',
      form: {
        id: null,
        courseName: '',
        status: '1',
        activityId: null,
        activityName: '', // 添加活动名称
        teacherId: null,
        teacherName:'',
        classId: null,
        className:''
      },
      activityList: [], // 用于存储活动名称列表
      teacherList:[],
      classList:[],
      rules: {
        courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    };
  },
  created() {
    this.fetchCourses();
    this.fetchActivities(); // 获取所有活动名称
    this.fetchTeachers();
    this.fetchClasses();

  },

  watch: {
    // 监听路由参数变化
    '$route.query.openDialog': {
      immediate: true,  // 确保组件创建时就执行一次
      handler(newVal) {
        if (newVal === 'create') {
          this.openAddDialog()
          // 清除 URL 参数
          this.$router.replace({
            path: this.$route.path,
            query: {}
          })
        }
      }
    }
  },
  methods: {
    openAddDialog() {
      this.dialogTitle = '新增课程';
      this.dialogVisible = true;
      this.form = {
        id: null,
        courseName: '',
        status: '1',
        activityName: '',
        teacherName: '',
        className: ''
      };
    },
    resetQuery() {
      this.activityName = "";
      this.courseName = "";
      this.status = "";
      this.teacherName = "";
      this.fetchCourses(1);
    },
    // 获取教学班数据
    selectCourses(page = 1) {
      const { activityName, courseName, status, teacherName, pageSize } = this;

      this.$axios
          .get("/course/select", {
            params: {
              activityName: activityName || undefined,  // 活动名称查询
              courseName: courseName || undefined,        // 教学班名称查询
              status: status || undefined,        // 描述查询
              teacherName: teacherName || undefined,    // 教师姓名查询
              currentPage: page,
              pageSize,
            },
            headers: {
              Authorization: localStorage.getItem("token"),
            },
          })
          .then((response) => {
            const data = response.data.data;
            this.courses = data.records || [];
            this.currentPage = data.current;
            this.total = data.total;

           /* this.courses = this.courses.map((courseItem) => {
              this.fetchTeacherName(courseItem.teacherId).then((teacherName) => {
                courseItem.teacherName = teacherName; // 设置教学班的教师名称
              });
              return courseItem;
            });*/

            // this.courses = this.courses.map((courseItem) => {
            //   this.fetchActivityName(courseItem.activityId).then((activityName) => {
            //     courseItem.activityName = activityName; // 设置教学班的活动名称
            //   });
            //   return courseItem;
            // });
          })
          .catch((error) => {
            console.error("课程数据查询失败：", error);
            this.$message.error("无法获取课程数据，请稍后重试");
          });
    },

    // 批量删除课程
    handleBatchDelete() {
      if (this.selectedCourses.length === 0) {
        ElMessage.error('请选择要删除的课程');
        return;
      }

      ElMessageBox.confirm('确定删除选中的课程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const courseIds = this.selectedCourses.map(course => course.id);
        this.$axios.post('/course/batch-delete', { ids: courseIds }, {
          headers: { Authorization: localStorage.getItem("token") }
        }).then(() => {
          ElMessage.success('删除成功');
          this.fetchCourses(); // 刷新课程列表
          this.selectedCourses = []; // 清空已选课程
        }).catch(error => {
          ElMessage.error('删除失败');
        });
      });
    },

    // 处理课程选择
    handleSelectionChange(selectedRows) {
      this.selectedCourses = selectedRows;
    },
    // 获取状态的文字表示
    getStatusText(status) {
      const statusMap = {
        "1": "启用",
        "0": "禁用",
        "2": "审核中",
      };
      return statusMap[status] || "未知状态";
    },
    // 获取课程列表
    fetchCourses() {
      this.$axios.get('/course/courses', {
        params: { currentPage: this.pagination.currentPage },
        headers: {
          Authorization: localStorage.getItem("token")
        }
      }).then((res) => {
        const data = res.data.data;
        this.courses = data.records;
        console.log("11111111111111111111111111111111")
        console.log(res.data.data.records)
        console.log("1111111111111111111111111111111111")
        this.pagination.total = data.total;
      }).catch((error) => {
        console.error('Error fetching courses:', error);
      });
    },
    // 格式化日期
    formatDate(date) {
      const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
      return new Date(date).toLocaleString('zh-CN', options);
    },
    // 状态标签类型
    statusType(status) {
      const types = { '1': 'success', '0': 'danger', '2': 'warning' };
      return types[status] || 'info';
    },
    // 分页处理
    handlePageChange(page) {
      this.pagination.currentPage = page;
      this.fetchCourses();
    },
    // 查看详情
    selectView(course) {
      this.dialogVisible1 = true;
      this.form = { ...course };  // 将课程信息填充到表单

      // 获取活动名称
      if (this.form.activityId) {
        this.fetchActivityName(this.form.activityId);  // 调用方法获取活动名称
      }
      if (this.form.classId) {
        this. fetchClassName(this.form.classId);  // 调用方法获取活动名称
      }
      if (this.form.teacherId) {
        this. fetchTeacherName(this.form.teacherId);  // 调用方法获取活动名称
      }

    },



    // 获取活动名称
    fetchActivityName(activityId) {
      this.$axios.get(`/manager-activity/activity/${activityId}`, {
        headers: {
          Authorization: localStorage.getItem("token")
        }
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.form.activityName = response.data.data.name;  // 将活动名称保存到form中
        } else {
          this.form.activityName = '活动信息加载失败';  // 如果没有获取到数据，显示失败信息
        }
      }).catch(error => {
        console.error('Error fetching activity name:', error);
        this.form.activityName = '活动信息加载失败';  // 错误时显示失败信息
      });
    },


    // 获取class名称
    fetchClassName(classId) {
      this.$axios.get(`/manager-class/class/${classId}`, {
        headers: {
          Authorization: localStorage.getItem("token")
        }
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.form.className= response.data.data.name;  // 将活动名称保存到form中
        } else {
          this.form.className = '教学班信息加载失败';  // 如果没有获取到数据，显示失败信息
        }
      }).catch(error => {
        console.error('Error fetching activity name:', error);
        this.form.className = '教学班信息加载失败';  // 错误时显示失败信息
      });
    },

    // 获取teacher名称
    fetchTeacherName(teacherId) {
      this.$axios.get(`/manager-teacher/teacher/${teacherId}`, {
        headers: {
          Authorization: localStorage.getItem("token")
        }
      }).then(response => {
        if (response.data.code === 200) {
          console.log(teacherId)
          console.log(response.data.data)
          this.form.teacherName= response.data.data.teacherName;  // 将活动名称保存到form中
        } else {
          this.form.teacherName = '教师信息加载失败';  // 如果没有获取到数据，显示失败信息
        }
      }).catch(error => {
        console.error('Error fetching activity name:', error);
        this.form.teacherName = '教师信息加载失败';  // 错误时显示失败信息
      });
    },
    // 编辑课程

    handleView(course){

      this.dialogVisible= true;
      this.form = { ...course }
      // 获取活动名称
      if (this.form.activityId) {
        this.fetchActivityName(this.form.activityId);  // 调用方法获取活动名称
      }
      if (this.form.classId) {
        this. fetchClassName(this.form.classId);  // 调用方法获取活动名称
      }
      if (this.form.teacherId) {
        this. fetchTeacherName(this.form.teacherId);  // 调用方法获取活动名称
      }
    },

    // 新增课程
   /* openAddDialog() {
      this.dialogTitle = '新增课程';
      this.dialogVisible = true;
      this.form = { id: null, courseName: '', status: '1' };
    },*/

    // 获取所有活动名称
    fetchActivities() {
      this.$axios.get('/manager-activity/all', {
        headers: { Authorization: localStorage.getItem("token") }
      }).then(response => {
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.activityList = response.data.data; // 将返回的活动列表赋值给 activityList
          console.log(this.activityList)
        } else {
          ElMessage.error('获取活动名称列表失败');
        }
      }).catch(error => {
        console.error('Error fetching activities:', error);
        ElMessage.error('获取活动名称列表失败');
      });
    },
    // 活动名称选择变化时的回调
    handleActivityChange(selectedActivityName) {
      // 可以在此处理选中的活动名称，做进一步的处理
      console.log('选中的活动名称:', selectedActivityName);
    },
    fetchTeachers() {
      this.$axios.get('/manager-teacher/all', {
        headers: { Authorization: localStorage.getItem("token") }
      }).then(response => {
        console.log(response.data.data)
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.teacherList = response.data.data; // 将返回的活动列表赋值给 activityList
          console.log(this.teacherList)
        } else {
          ElMessage.error('获取教师名称列表失败');
        }
      }).catch(error => {
        console.error('Error fetching teachers:', error);
        ElMessage.error('获取教师名称列表失败');
      });
    },
    // 活动名称选择变化时的回调
    handleTeacherChange(selectedTeacherName) {
      // 可以在此处理选中的活动名称，做进一步的处理
      console.log('选中的活动名称:', selectedTeacherName);
    },


    fetchClasses() {
      this.$axios.get('/manager-class/all', {
        headers: { Authorization: localStorage.getItem("token") }
      }).then(response => {
        console.log(response.data.data)
        if (response.data.code === 200) {
          console.log(response.data.data)
          this.classList = response.data.data; // 将返回的活动列表赋值给 activityList
          console.log(this.classList)
        } else {
          ElMessage.error('获取教学班名称列表失败');
        }
      }).catch(error => {
        console.error('Error fetching teachers:', error);
        ElMessage.error('获取教学班名称列表失败');
      });
    },
    // 活动名称选择变化时的回调
    handleClassChange(selectedTeacherName) {
      // 可以在此处理选中的活动名称，做进一步的处理
      console.log('选中的活动名称:', selectedTeacherName);
    },

    // 保存课程

    handleSave() {
      const courseData = {
        id: this.form.id, // 确保传递课程 ID，用于更新操作
        courseName: this.form.courseName,
        status: this.form.status,
        teacherName: this.form.teacherName,
        className: this.form.className,
        activityName: this.form.activityName
      };
      this.$axios.post('/course/update', courseData, {
        headers: { Authorization: localStorage.getItem("token") }
      }).then(response => {
        ElMessage.success('课程保存成功');
        this.fetchCourses();
      }).catch(error => {
        ElMessage.error('课程保存失败');
      });
    },




    // 删除课程
    deleteCourse(id) {
      ElMessageBox.confirm('确定删除该课程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.delete(`/course/delete/${id}`, {
          headers: { Authorization: localStorage.getItem("token") }
        }).then(() => {
          ElMessage.success('删除成功');
          this.fetchCourses();
        });
      });
    }
  }
};
</script>

<template>
  <div>
    <el-card class="box-card">

      <div class="clearfix" style="margin-bottom: 40px">

        <!-- 查询区域 -->
        <el-row gutter="20" class="search-bar">
          <el-col :span="3">
            <el-select
                v-model="courseName"
                placeholder="按课程名称查询"
                clearable
                size="small"
            >
              <el-option
                  v-for="course in courses"
                  :key="course.id"
                  :label="course.courseName"
                  :value="course.courseName"
              />
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select
                v-model="status"
                placeholder="按状态查询"
                clearable
                size="small"
            >
              <el-option label="已发布" value="1"></el-option>
              <el-option label="已结束" value="0"></el-option>
              <el-option label="创建" value="2"></el-option>
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-select
                v-model="activityName"
                placeholder="按活动名称查询"
                clearable
                size="small"
            >
              <el-option
                  v-for="activity in activityList"
                  :key="activity.id"
                  :label="activityList.name"
                  :value="activity.name"
              />
            </el-select>
          </el-col>

          <el-col :span="4">
            <el-select
                v-model="teacherName"
                placeholder="按教师名称查询"
                clearable
                size="small"
            >
              <el-option
                  v-for="teacher in teacherList"
                  :key="teacher.id"
                  :label="teacher.teacherName"
                  :value="teacher.teacherName"
              />
            </el-select>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" size="small" @click="selectCourses(1)">
              查询
            </el-button>
            <el-button size="small" @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="openAddDialog" size="small" style="float: left;">新增课程</el-button>
            <!-- 批量删除按钮 -->
            <el-button type="danger" size="small" @click="handleBatchDelete" style="float: left; margin-right: 10px;" :disabled="selectedCourses.length === 0">批量删除</el-button>
          </el-col>
        </el-row>








      </div>
      <el-table :data="courses" style="width: 100%" border @selection-change="handleSelectionChange">
        <!-- 选择框 -->
        <el-table-column type="selection" width="55" :selectable="selectable"></el-table-column>
        <!-- ID -->
        <el-table-column prop="id" label="ID" width="80"></el-table-column>

        <!-- 课程名称 -->
        <el-table-column prop="courseName" label="课程名称" width="180"></el-table-column>

        <!-- 创建时间 -->
        <el-table-column prop="createdTime" label="创建时间" width="200">
          <template #default="scope">
            {{ formatDate(scope.row.createdTime) }}
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="statusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="selectView(scope.row)">详情</el-button>
            <el-button size="small" type="primary" @click="handleView(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCourse(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: right;">
        <el-pagination
            background
            layout="prev, pager, next"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="课程信息">

      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="form.courseName"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="已发布" value="1"></el-option>
            <el-option label="已结束" value="0"></el-option>
            <el-option label="创建" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称" prop="activityName">
          <el-select v-model="form.activityName" placeholder="请选择活动名称" @change="handleActivityChange">
            <el-option
                v-for="activity in activityList"
                :key="activity.id"
                :label="activity.name"
                :value="activity.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教师名称" prop="teacherName">
          <el-select v-model="form.teacherName" placeholder="请选择教师名称" @change="handleTeacherChange">
            <el-option
                v-for="teacher in teacherList"
                :key="teacher.id"
                :label="teacher.teacherName"
                :value="teacher.teacherName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教学班名称" prop="className">
          <el-select v-model="form.className" placeholder="请选择教学班名称" @change="handleClassChange">
            <el-option
                v-for="class1 in classList"
                :key="class1.id"
                :label="class1.name"
                :value="class1.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible1" title="课程信息">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="课程名称">{{form.courseName }}</el-descriptions-item>
        <el-descriptions-item label="活动名称">{{form.activityName }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ getStatusText(form.status) }}</el-descriptions-item>
        <el-descriptions-item label="教师名称">{{form.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="教学班名称">{{form.className }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible1 = false">关闭</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>
<style>
.clearfix{
  margin-bottom: 5px;
}
</style>